document.addEventListener('DOMContentLoaded', function() {
    const configForm = document.getElementById('config-form');
    const resetBtn = document.getElementById('reset-btn');
    const saveBtn = document.getElementById('save-btn');
    
    // 保存原始表单数据
    const originalFormData = {
        'douban-cookie': document.getElementById('douban-cookie')?.value || '',
        'user-agent': document.getElementById('user-agent')?.value || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'tmdb-api-key': document.getElementById('tmdb-api-key')?.value || '',
        'tmdb-proxy-ip': document.getElementById('tmdb-proxy-ip')?.value || 'localhost',
        'tmdb-proxy-port': document.getElementById('tmdb-proxy-port')?.value || '7890',
        'javdb-cookie': document.getElementById('javdb-cookie')?.value || '',
        'ptskit-cookie': document.getElementById('ptskit-cookie')?.value || '',
        'qb-host': document.getElementById('qb-host')?.value || 'localhost',
        'qb-port': document.getElementById('qb-port')?.value || '8080',
        'qb-username': document.getElementById('qb-username')?.value || 'admin',
        'qb-password': document.getElementById('qb-password')?.value || 'adminadmin',
        'tr-host': document.getElementById('tr-host')?.value || 'localhost',
        'tr-port': document.getElementById('tr-port')?.value || '9091',
        'tr-username': document.getElementById('tr-username')?.value || 'username',
        'tr-password': document.getElementById('tr-password')?.value || 'password',
        'fnos-media-server-ip': document.getElementById('fnos-media-server-ip')?.value || 'localhost',
        'fnos-media-server-port': document.getElementById('fnos-media-server-port')?.value || '5666',
        'fnos-media-username': document.getElementById('fnos-media-username')?.value || 'username',
        'fnos-media-password': document.getElementById('fnos-media-password')?.value || 'password',
        'emby-server-url': document.getElementById('emby-server-url')?.value || 'localhost',
        'emby-server-port': document.getElementById('emby-server-port')?.value || '8096',
        'emby-api-key': document.getElementById('emby-api-key')?.value || '',
        'emby-user-id': document.getElementById('emby-user-id')?.value || ''
    };
    
    // 重置按钮点击事件
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            // 检查是否有更改
            const hasChanges = Object.keys(originalFormData).some(key => {
                return document.getElementById(key).value !== originalFormData[key];
            });
            
            if (!hasChanges) {
                showNotification('没有需要重置的更改', 'info');
                return;
            }
            
            if (confirm('确定要重置配置吗？当前未保存的更改将会丢失。')) {
                // 重置表单值
                Object.keys(originalFormData).forEach(key => {
                    document.getElementById(key).value = originalFormData[key];
                });
                showNotification('配置已重置', 'info');
            }
        });
    }
    
    // 表单提交事件
    if (configForm && saveBtn) {
        configForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 构建配置对象
            const configData = {
                douban: {
                    cookie: document.getElementById('douban-cookie').value,
                    user_agent: document.getElementById('user-agent').value
                },
                tmdb: {
                    api_key: document.getElementById('tmdb-api-key').value,
                    proxy_ip: document.getElementById('tmdb-proxy-ip').value,
                    proxy_port: document.getElementById('tmdb-proxy-port').value
                },
                javdb: {
                    cookie: document.getElementById('javdb-cookie').value
                },
                ptskit: {
                    cookie: document.getElementById('ptskit-cookie').value
                },
                qbittorrent: {
                    host: document.getElementById('qb-host').value,
                    port: parseInt(document.getElementById('qb-port').value),
                    username: document.getElementById('qb-username').value,
                    password: document.getElementById('qb-password').value
                },
                transmission: {
                    host: document.getElementById('tr-host').value,
                    port: parseInt(document.getElementById('tr-port').value),
                    username: document.getElementById('tr-username').value,
                    password: document.getElementById('tr-password').value
                },
                app: {
                    data_dir: document.getElementById('data-dir').value,
                    nfo_dir: document.getElementById('nfo-dir').value,
                    image_dir: document.getElementById('image-dir').value
                },
                // 飞牛媒体库配置
                fnos_media: {
                    server_ip: document.getElementById('fnos-media-server-ip').value,
                    server_port: parseInt(document.getElementById('fnos-media-server-port').value),
                    username: document.getElementById('fnos-media-username').value,
                    password: document.getElementById('fnos-media-password').value,
                    verify_ssl: document.getElementById('fnos-media-verify-ssl').checked
                },
                // Emby媒体服务器配置
                emby: {
                    server_url: document.getElementById('emby-server-url').value,
                    server_port: parseInt(document.getElementById('emby-server-port').value),
                    api_key: document.getElementById('emby-api-key').value,
                    user_id: document.getElementById('emby-user-id').value
                }
            };
            
            // 显示加载状态
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
            
            // 发送请求更新配置
            fetch('/api/config/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 添加CSRF令牌（如果需要）
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify(configData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 更新原始数据，避免重置时认为有更改
                    originalFormData['douban-cookie'] = document.getElementById('douban-cookie').value;
                    originalFormData['user-agent'] = document.getElementById('user-agent').value;
                    originalFormData['ptskit-cookie'] = document.getElementById('ptskit-cookie').value;
                    originalFormData['qb-host'] = document.getElementById('qb-host').value;
                    originalFormData['qb-port'] = document.getElementById('qb-port').value;
                    originalFormData['qb-username'] = document.getElementById('qb-username').value;
                    originalFormData['qb-password'] = document.getElementById('qb-password').value;
                    originalFormData['tr-host'] = document.getElementById('tr-host').value;
                    originalFormData['tr-port'] = document.getElementById('tr-port').value;
                    originalFormData['tr-username'] = document.getElementById('tr-username').value;
                    originalFormData['tr-password'] = document.getElementById('tr-password').value;
                    
                    // 更新飞牛媒体库配置的原始数据
                    originalFormData['fnos-media-server-ip'] = document.getElementById('fnos-media-server-ip').value;
                    originalFormData['fnos-media-server-port'] = document.getElementById('fnos-media-server-port').value;
                    originalFormData['fnos-media-username'] = document.getElementById('fnos-media-username').value;
                    originalFormData['fnos-media-password'] = document.getElementById('fnos-media-password').value;
                    
                    // 更新Emby媒体服务器配置的原始数据
                    originalFormData['emby-server-url'] = document.getElementById('emby-server-url').value;
                    originalFormData['emby-server-port'] = document.getElementById('emby-server-port').value;
                    originalFormData['emby-api-key'] = document.getElementById('emby-api-key').value;
                    originalFormData['emby-user-id'] = document.getElementById('emby-user-id').value;
                    
                    // 更新TMDB配置的原始数据
                    originalFormData['tmdb-api-key'] = document.getElementById('tmdb-api-key').value;
                    originalFormData['tmdb-proxy-ip'] = document.getElementById('tmdb-proxy-ip').value;
                    originalFormData['tmdb-proxy-port'] = document.getElementById('tmdb-proxy-port').value;
                    
                    // 更新Javdb配置的原始数据
                    originalFormData['javdb-cookie'] = document.getElementById('javdb-cookie').value;
                    
                    showNotification('配置更新成功', 'success');
                } else {
                    showNotification('配置更新失败: ' + (data.message || '未知错误'), 'error');
                }
            })
            .catch(error => {
                showNotification('配置更新失败: ' + error.message, 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                saveBtn.disabled = false;
                saveBtn.innerHTML = '<i class="fa fa-save mr-2"></i> 保存配置';
            });
        });
    }
    
    // 获取Cookie的辅助函数（用于CSRF令牌）
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    // 显示通知的辅助函数
    function showNotification(message, type = 'info') {
        // 检查是否已经存在通知函数，如果没有则创建一个简单的
        if (window.showNotification) {
            window.showNotification(message, type);
        } else {
            // 创建一个简单的通知
            const notification = document.createElement('div');
            notification.className = `fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 ${type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'} text-white`;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            // 3秒后移除通知
            setTimeout(() => {
                notification.style.opacity = '0';
                notification.style.transition = 'opacity 0.5s ease';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 500);
            }, 3000);
        }
    }
});